package kr.hkit.masan_alarm;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Masan_main extends Activity implements OnInitListener {
	EditText editT;
	ImageButton imgBtn;
	
	private SharedPreferences pref;
	private MyCursorAdapter adapter;
	private ListView list;
	private DB_Manager db;
	private Cursor currentCursor;
	//
	private static int colID;
	private static int colONOFF;
	private static int colHOUR;
	private static int colMINUTE;
	private static int colDAY;
	private static int colVIB;
	private static int colRING;
	//
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.masan_main);
		
		db = new DB_Manager(this);
        db.open();
        
        currentCursor = db.fetchAllAlarm();
		
		String[] from = new String[] {DB_Manager.ALARM_HOUR, DB_Manager.ALARM_MINUTE};
   		int[] to = new int[] {R.id.row_time, R.id.row_day};
		
		list = (ListView) findViewById(R.id.list);
		list.setOnTouchListener(onTouchListener);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				currentCursor.moveToPosition(position);
				ImageView icon_view = (ImageView)view.findViewById(R.id.tgButton);
				ImageView delete_view = (ImageView)view.findViewById(R.id.row_delete);
				
				//
				if (QuickMenuEvent == MotionEvent.ACTION_UP) {
					if (icon_view.getLeft() < CheckedColumn_x && CheckedColumn_x < icon_view.getRight()) {
						long db_id = currentCursor.getLong(colID);
						int on = currentCursor.getInt(colONOFF);
						//
						if (on == 0){
							on = 1; 
						}else{
							on = 0;
						}
						//
						db.modifyAlarmOn(db_id, on);
						currentCursor = db.fetchAllAlarm();
						adapter.notifyDataSetChanged();
						//
						if(on == 1){	
							icon_view.setImageResource(R.drawable.clock_on);
							Toast.makeText(getBaseContext(), "알람시작", Toast.LENGTH_SHORT).show();
						} else {
							icon_view.setImageResource(R.drawable.clock_off);
							Toast.makeText(Masan_main.this, "알람정지", Toast.LENGTH_SHORT).show();
						}
						
					} else if (delete_view.getLeft() < CheckedColumn_x && 
							CheckedColumn_x < delete_view.getRight()) {
						new AlertDialog.Builder(Masan_main.this)
	    				.setMessage("삭제하시겠습니까?")
	    				.setCancelable(false)
	    				.setPositiveButton("네",
	    						new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										long db_id = currentCursor.getLong(colID);
										db.delAlarm("" + db_id);
										currentCursor = db.fetchAllAlarm();
										adapter.notifyDataSetChanged();
										Masan_info.cancelAlarm(Masan_main.this);
										Masan_info.startFirstAlarm(Masan_main.this);
									}
								})
						.setNegativeButton("아뇨", null)
						.show();
					} else{
						long db_id = currentCursor.getLong(colID);
						
						 Intent intent = new Intent(Masan_main.this, Masan_set.class);
						 intent.putExtra("id", db_id);
						 intent.putExtra("day", currentCursor.getInt(colDAY));
						 intent.putExtra("hour", currentCursor.getInt(colHOUR));
						 intent.putExtra("min", currentCursor.getInt(colMINUTE));
						 intent.putExtra("ring", currentCursor.getString(colRING));
						 intent.putExtra("vib", currentCursor.getInt(colVIB));

						 startActivity(intent);
					}
				
				}
			}
		});
		
		adapter = new MyCursorAdapter(list.getContext(), R.layout.list_row, currentCursor, from, to);
		list.setAdapter(adapter);  
		
		colID = currentCursor.getColumnIndex("_id"); 
        colONOFF = currentCursor.getColumnIndex(DB_Manager.ALARM_ON);
        colDAY = currentCursor.getColumnIndex(DB_Manager.ALARM_APDAY);
        colHOUR = currentCursor.getColumnIndex(DB_Manager.ALARM_HOUR); 
        colMINUTE = currentCursor.getColumnIndex(DB_Manager.ALARM_MINUTE);
        colRING = currentCursor.getColumnIndex(DB_Manager.ALARM_RINGTONE);
        colVIB = currentCursor.getColumnIndex(DB_Manager.ALARM_VIBRATE);
        
        // pref text
		editT = (EditText) findViewById(R.id.edit_main);
		
		pref = getSharedPreferences("PrefEdit", 0);
		String text = pref.getString("text", "활기찬 문구를 입력하세요");
		editT.setText(text);
		// /pref text
	
		// alarm add
		imgBtn = (ImageButton) findViewById(R.id.btn_add);
		imgBtn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Masan_main.this, Masan_set.class);
				startActivity(intent);
			}
		});
	}//onCreate
	
	private static int QuickMenuEvent = 0; 
	private static float CheckedColumn_x = 0;
	
    OnTouchListener onTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch (View view, MotionEvent event) { 
    		CheckedColumn_x = event.getX();
    		QuickMenuEvent = event.getAction();

    		return false;
    	}
    };
	

	@Override
	protected void onResume() {
		super.onResume();
		currentCursor = db.fetchAllAlarm();
		adapter.notifyDataSetChanged();
	}//onResume


	@Override
	protected void onPause() {
		super.onPause();
		pref = getSharedPreferences("PrefEdit", 0);
		SharedPreferences.Editor edit = pref.edit();
		
		String text = editT.getText().toString();
		
		edit.putString("text", text);
		
		edit.commit();
	}//onPause


	@Override
	public void onInit(int status) {
	}//onInit
	
	private class MyCursorAdapter extends SimpleCursorAdapter {
		Context mContext;
		private int mRowLayout;
		
		@SuppressWarnings("deprecation")
		public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);
			mContext = context;
			mRowLayout = layout;
		}
		
		@Override
		public int getCount() {
			return currentCursor.getCount();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			currentCursor.moveToPosition(position);
			ViewHolder viewHolder;
			
			if (convertView == null) {
				LayoutInflater inflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);         
				convertView = inflater.inflate(mRowLayout, parent, false);
				viewHolder = new ViewHolder();     
      	        viewHolder.icon = (ImageView)convertView.findViewById(R.id.tgButton);
      	        viewHolder.time = (TextView)convertView.findViewById(R.id.row_time);
      	        viewHolder.day = (TextView)convertView.findViewById(R.id.row_day);
      	        //
      	        convertView.setTag(viewHolder);
			} else {
      			viewHolder = (ViewHolder)convertView.getTag();
			}
			//
			viewHolder.time.setText(getTimeString(currentCursor.getInt(colHOUR), currentCursor.getInt(colMINUTE)));
			
			int day = currentCursor.getInt(colDAY);
			String strDay="";
			if((day & 0x01) == 0x01){ strDay = "일"; }
			if((day & 0x02) == 0x02){ strDay += "월"; }
			if((day & 0x04) == 0x04){ strDay += "화"; }
			if((day & 0x08) == 0x08){ strDay += "수"; }
			if((day & 0x10) == 0x10){ strDay += "목"; }
			if((day & 0x20) == 0x20){ strDay += "금"; }
			if((day & 0x40) == 0x40){ strDay += "토"; }
			//
			viewHolder.day.setText(strDay);
			//
			int on = currentCursor.getInt(colONOFF);
			
			if(on == 1)	viewHolder.icon.setImageResource(R.drawable.clock_on);
			else viewHolder.icon.setImageResource(R.drawable.clock_off); 
			//
			return convertView;
		}
		
    	private class ViewHolder {
    	 	ImageView icon;
    	 	TextView time;
    	 	TextView day;
    	};    	    

	}
	
    public String getTimeString(int h, int m) {
    	 Calendar cal = Calendar.getInstance();
     	 cal.set(Calendar.HOUR_OF_DAY, h);
     	 cal.set(Calendar.MINUTE, m);
     	 SimpleDateFormat dayformat = new SimpleDateFormat("HH:mm");
     	 dayformat.setCalendar(cal);
     	 Date date = cal.getTime();
     	 return dayformat.format(date);
  }
    
}
